'use strict';

const Controller = require('egg').Controller;

class BlogController extends Controller {
  // 获取book页面
  async getBlogList() {
    const blogList = await this.ctx.service.blog.getBlogList();
    const { ctx } = this;
    await ctx.render("/pc/blog.html",{
        blogList
    })
  }

//   给前端写的端口
  // post添加操作
  async create() {
    try {
        const body = this.ctx.request.body;
        body.orderby = Number(body.orderby)  // 把orderby转换为数字格式
        await this.ctx.service.blog.createBlog(body)   // 传递获取到的body给服务层的book.js的createBook方法
        this.ctx.body = {
            code: 20000,
            message: true,
        }
    } catch (error) {
        this.ctx.body = {
            code: 30000,
            message: false,
        }
    }
}
// 查
async index() {
  try {
    //   const query = this.ctx.request.query;
      const blogList = await this.ctx.service.blog.getBlogList(); 
        console.log("index方法的blogList",blogList);
      this.ctx.body = {
          code: 20000,
          message: true,
          data: blogList,
      }
  } catch (error) {
      this.ctx.body = {
          code: 30000,
          message: false,
      }
  }
}
//查找指定的一篇博客(这好像是给前端写的端口)
async show() {
    try {
        const id = await this.ctx.params.id
        const blog = await this.ctx.service.blog.getBlogDetail(id)
        console.log("我是show里面的blog",blog);
        this.ctx.body = {
            code: 20000,
            message: true,
            data: blog
        }
    } catch (error) {
        this.ctx.body = {
            code: 20000,
            message: false,
        }
    }
}
async getBlogDetail(){   //按条件查询
        let id = this.ctx.params.id;
        // await console.log("我是获取到的id",id);
        const blog = await this.ctx.service.blog.getBlogDetail(id)
        await console.log("我是controller处的blogList的id",blog);
        await this.ctx.render("/pc/blog_detail.html",{blog})
}

// 修改
async update() {
    try {
        const body = this.ctx.request.body;
        const id = this.ctx.params.id;
        await this.ctx.service.blog.updateBlog(id, body)
        this.ctx.body = {
            code: 20000,
            data: true
        }
    } catch (error) {
        this.ctx.body = {
            code: 30000,
            message: false
        }
    }
}
    // 删除
async destroy(){
    try{
        let id = this.ctx.params.id;
        await this.ctx.service.blog.deleteBlog(id)
        this.ctx.body = {
            code:20000,
            data:true
        } 
    }catch(error){
        this.ctx.body = {
            code:30000,
            message:false
        }
        
    }
  }

 
}

module.exports = BlogController;
